package com.smalluz.ad.modules.common.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Slf4j
public class OkHttpUtils {
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    
    private static final OkHttpClient client = new OkHttpClient().newBuilder().build();
    /**
     * Send POST request
     *
     * @param jsonStr Args in JSON format
     * @return Response in JSON format
     */
    public String post(String path, String jsonStr) {
        
        try {
            log.info("~~~请求地址：{}  ",path);
            RequestBody body = RequestBody.create(jsonStr,JSON);
            Request request = new Request.Builder()
                    .url(path)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    //.addHeader("X-Debug-Mode", "1")
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

        return "";
    }
    
    public String postKs(String accessToken, String path, String jsonStr) {
        
        try {
            log.info("~~~请求地址：{}  ",path);
            RequestBody body = RequestBody.create(jsonStr,JSON);
            Request request = new Request.Builder()
                    .url(path)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Access-Token", accessToken)
                    //.addHeader("X-Debug-Mode", "1")
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

        return "";
    }
    
    public String get(String accessToken, String path, String jsonStr) {

        // 构造请求
        HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                return "GET";
            }
        };
        
        if(StringUtils.isNotBlank(accessToken)) {
            httpEntity.setHeader("Access-Token", accessToken);
        }
        
        httpEntity.setHeader("X-Debug-Mode", "1");
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        //log.info("~~~请求地址：{}  ",path);
        log.info("~~~请求参数：{}  ", jsonStr);
        try {
            client = HttpClientBuilder.create().build();
            httpEntity.setURI(URI.create(path));
            httpEntity.setEntity(new StringEntity(jsonStr, ContentType.APPLICATION_JSON));

            response = client.execute(httpEntity);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                return result.toString();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
}
